package com.example.shiro;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

public class JdbcRealmTest {

    DruidDataSource dataSource = new DruidDataSource();

    {
        dataSource.setUrl("jdbc:mysql://localhost:3306/shiro-test?characterEncoding=utf-8&serverTimezone=UTC&useSSL=true");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
    }


    void testShiro(){
        //构建 SecurityManager
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        JdbcRealm jdbcRealm = new JdbcRealm();
        jdbcRealm.setDataSource(dataSource);
        //默认是 false 请设置为true
        jdbcRealm.setPermissionsLookupEnabled(true);
        //设置登录相关语句.
        jdbcRealm.setAuthenticationQuery("select password from userinfo where username = ? ");
        //设置角色相关语句.
        jdbcRealm.setUserRolesQuery("select role_name from roles where username = ? ");
        //设置资源相关语句.
        jdbcRealm.setPermissionsQuery("select permission_name from permissions where role_name = ? ");

        securityManager.setRealm(jdbcRealm);

        //主体认证提交请求
        //用户传过来的数据   和reaml里面的进行匹配
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("admin","123456");
        //认证
        subject.login(token);


        //授权  是否有 user角色
        subject.checkRole("user");

        //资源
        subject.checkPermission("permit:delete");

        subject.checkPermission("permit:update");

        System.out.println("admin is login : " + subject.isAuthenticated());
        subject.logout();
        System.out.println("admin is login : " + subject.isAuthenticated());



    }

    public static void main(String[] args) {
        JdbcRealmTest test = new JdbcRealmTest();
        test.testShiro();
    }

}
